package com.huanzhidadi.single.compare;

import com.alibaba.fastjson2.JSON;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Collections.sort
 */
public class ComparatorTest {
    //构造一个排序比较器
    static Comparator comparator = new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            /***
             * 升序，大的排后面
             *该函数返回值r
             * r > 0, o1排到o2后面
             * r < 0, o1排在o2前面
             * r ==0 , o1和o2顺序不变
             */
            if(o1.compareToIgnoreCase(o2) > 0)
                return 1;
            else if (o1.compareToIgnoreCase(o2) < 0)
                return -1;
            else return 0;
        }
    };


    public static void main(String[] args) {
        String[] str = new String[] {"a", "c", "b", "1", "10", "9"};
        // 数组排序
        /*System.out.println("数组排序");
        Arrays.stream(str).forEach(System.out::print);
        Arrays.sort(str, comparator);
        System.out.println("");
        Arrays.stream(str).forEach(System.out::print);
        System.out.println("");*/


        //集合排序
        System.out.println("集合排序");
        List<String> list = Arrays.stream(str).collect(Collectors.toList());
        System.out.println(JSON.toJSONString(list));
        Collections.sort(list);
        System.out.println("");
        System.out.println(JSON.toJSONString(list));
        Collections.sort(list, comparator);
        System.out.println("");
        System.out.println(JSON.toJSONString(list));
    }
}
